package com.golden.procedure.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.golden.procedure.dao.SiteSchedulingTemplateDetailMapper;
import com.golden.procedure.dao.SiteSchedulingTemplateMapper;
import com.golden.procedure.dao.WorkSeatSchedulingMapper;
import com.golden.procedure.domain.SiteTemplateDO;
import com.golden.procedure.domain.SiteTemplateDetailDO;
import com.golden.procedure.domain.WorkSeatSchedulingDO;
import com.golden.procedure.domain.WorkSiteSeatDO;
import com.golden.procedure.entity.SiteSchedulingTemplate;
import com.golden.procedure.entity.SiteSchedulingTemplateDetail;
import com.golden.procedure.entity.SiteSchedulingTemplateDetailExample;
import com.golden.procedure.entity.SiteSchedulingTemplateExample;
import com.golden.procedure.query.SchedulingQueryDO;
import com.golden.procedure.query.SiteTemplateQueryDO;
import com.golden.procedure.result.ResultDO;
import com.golden.procedure.result.ResultSupport;
import com.golden.procedure.service.ISiteTemplateService;
import com.golden.procedure.util.BeanUtilsExtends;
import com.golden.procedure.util.BonConstant;

@Service("siteTemplateService")
public class SiteTemplateService extends BaseService implements ISiteTemplateService {

	@Autowired
	SiteSchedulingTemplateMapper siteTemplateMapper;
	@Autowired
	SiteSchedulingTemplateDetailMapper siteTemplateDetailMapper;
	@Autowired
	WorkSeatSchedulingMapper workSeatSchedulingMapper;
	@Autowired
	WorkSiteSchedulingService workSiteSchedulingService;

	/**
	 * 另保存为新模板/更新其他模板 <b>Description:</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午3:57:51 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO addFromTemplate(SiteTemplateDO domain) {
		// 原模板保存为新模板/或更新其他模板
		ResultDO result = new ResultSupport();
		// 1. 数据验证
		if (isNumberInValid(domain.getSiteID()) || isNumberInValid(domain.getSrcTemplateID())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误： 上门组ID无效");
			result.setSuccess(false);
		}

		// 2.读取源模版数据
		SiteSchedulingTemplate entity = siteTemplateMapper.selectByPrimaryKey(domain.getSrcTemplateID());
		if (null == entity) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("未找到模板");
			result.setSuccess(false);
			return result;
		}
		// 3.读取源模板详情
		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andTemplateIDEqualTo(entity.getId());
		criteria.andIsDeleteEqualTo(1);
		example.setOrderByClause(" seatGroupIndex, planStartOn ");

		List<SiteSchedulingTemplateDetail> srcList = siteTemplateDetailMapper.selectByExample(example);
		if (null == srcList || srcList.isEmpty()) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("模板详情未找到");
			result.setSuccess(false);
			return result;
		}

		if (isNumberInValid(domain.getDestTemplateID())) {
			// 4.创建新模板
			entity.setId(null);
			entity.setTemplateName(domain.getTemplateName());
			int ret = siteTemplateMapper.insert(entity);

			if (ret != 1) {
				// 模板写入失败
				result.setErrorCode(ResultDO.PARAM_ERROR);
				result.setErrorMsg("模板创建失败");
				result.setSuccess(false);
				return result;
			}
		} else {
			// 5. 更新模板： 先删除原模板数据
			entity.setId(domain.getDestTemplateID());

			SiteSchedulingTemplateDetailExample example1 = new SiteSchedulingTemplateDetailExample();
			SiteSchedulingTemplateDetailExample.Criteria criteria1 = example.createCriteria();
			criteria1.andTemplateIDEqualTo(domain.getDestTemplateID());
			siteTemplateDetailMapper.deleteByExample(example1);
		}

		// 6.创建新模板详情
		for (SiteSchedulingTemplateDetail data : srcList) {
			data.setTemplateID(entity.getId());
			data.setId(null);
			data.setAuthor(domain.getAuthor());
			data.setAuthorID(domain.getAuthorID());
			data.setCreatetime(Calendar.getInstance().getTime());
		}
		siteTemplateDetailMapper.insertBatch(srcList);
		return result;
	}

	/**
	 * 从摄控设置 保存为模板 <b>Description:</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午3:58:35 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO addFromSetting(SiteTemplateDO domain) {
		// 创建摄控设置时，保存为新模板/更新原有模板
		ResultDO result = new ResultSupport();
		// 1. 数据验证
		if (isNumberInValid(domain.getSiteID())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误： 上门组ID无效");
			result.setSuccess(false);
		}

		// 2.读取设置数据详情
		SchedulingQueryDO query = new SchedulingQueryDO();
		query.setSiteID(domain.getSiteID());
		query.setSchedulingDateStart(domain.getSchedulingDateStart());
		query.setSchedulingDateEnd(domain.getSchedulingDateEnd());

		ResultDO resultDO = workSiteSchedulingService.query(query);
		if (!resultDO.isSuccess()) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("摄控数据查询失败");
			result.setSuccess(false);
			return result;
		}

		List<WorkSiteSeatDO> seatDOList = (List<WorkSiteSeatDO>) resultDO.getModel(ResultDO.FIRST_MODEL_KEY);
		if (null == seatDOList || seatDOList.isEmpty()) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("摄控数据为空");
			result.setSuccess(false);
			return result;
		}

		SiteSchedulingTemplate entity = new SiteSchedulingTemplate();
		if (isNumberInValid(domain.getDestTemplateID())) {
			// 3.新增模板
			entity.setTemplateName(domain.getTemplateName());
			entity.setSitetID(domain.getSiteID());
			entity.setIsDelete(BonConstant.DB_NORMAL);
			entity.setAuthorID(domain.getAuthorID());
			entity.setAuthor(domain.getAuthor());

			int ret = siteTemplateMapper.insert(entity);
			if (ret != 1) {
				result.setErrorCode(ResultDO.PARAM_ERROR);
				result.setErrorMsg("模板创建失败");
				result.setSuccess(false);
				return result;
			}
		} else {
			// 4. 更新模板： 先删除原模板数据
			entity.setId(domain.getDestTemplateID());

			SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
			SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
			criteria.andTemplateIDEqualTo(domain.getDestTemplateID());
			siteTemplateDetailMapper.deleteByExample(example);
		}

		// 4.新增模板详情
		List<SiteSchedulingTemplateDetail> detailList = new ArrayList<SiteSchedulingTemplateDetail>();
		for (WorkSiteSeatDO siteSeatDO : seatDOList) {
			// 分组
			List<WorkSeatSchedulingDO> list = siteSeatDO.getSeatList();
			for (WorkSeatSchedulingDO seatDO : list) {
				// 席位
				SiteSchedulingTemplateDetail detail = new SiteSchedulingTemplateDetail();
				detail.setTemplateID(entity.getId());
				detail.setSeatGroupIndex(siteSeatDO.getSeatGroupIndex());
				detail.setPlanStartOn(seatDO.getPlanStartOn());
				detail.setStatus(seatDO.getStatus());
				detail.setIsDelete(BonConstant.DB_NORMAL);
				detail.setAuthor(domain.getAuthor());
				detail.setAuthorID(domain.getAuthorID());
				detail.setCreatetime(Calendar.getInstance().getTime());
				detail.setAuthorID(domain.getAuthorID());
				detail.setAuthor(domain.getAuthor());
				detailList.add(detail);
			}
		}
		siteTemplateDetailMapper.insertBatch(detailList);

		return result;
	}

	/**
	 * 根据景点id查询模板列表 <b>Description:</b><br>
	 * 
	 * @param query
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午3:58:50 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO query(SiteTemplateQueryDO query) {
		// 查询模板列表
		ResultDO result = new ResultSupport();
		// 1. 数据验证
		if (isNumberInValid(query.getSiteID())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
		}

		// 2.按上门组ID查询
		SiteSchedulingTemplateExample example = new SiteSchedulingTemplateExample();
		SiteSchedulingTemplateExample.Criteria criteria = example.createCriteria();
		criteria.andSitetIDEqualTo(query.getSiteID());
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		List<SiteSchedulingTemplate> srcList = siteTemplateMapper.selectByExample(example);
		List<SiteTemplateDO> dstList = new ArrayList<SiteTemplateDO>();
		if (null != srcList && srcList.size() > 0) {
			for (SiteSchedulingTemplate entity : srcList) {
				SiteTemplateDO templateDO = new SiteTemplateDO();
				if (BeanUtilsExtends.copyProperties(templateDO, entity)) {
					dstList.add(templateDO);
				}
			}
		}
		result.setModel(ResultDO.FIRST_MODEL_KEY, dstList);
		return result;
	}

	/**
	 * 根据模板id查询模板详情 <b>Description:</b><br>
	 * 
	 * @param query
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午3:59:13 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO queryDetail(SiteTemplateQueryDO query) {
		// 查询模板详情
		ResultDO result = new ResultSupport();
		// 1. 数据验证
		if (isNumberInValid(query.getId())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误： 模板ID无效");
			result.setSuccess(false);
			return result;
		}

		// 2.查询设置详情
		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andTemplateIDEqualTo(query.getId());
		criteria.andIsDeleteEqualTo(1);
		example.setOrderByClause(" seatGroupIndex, planStartOn ");

		List<SiteSchedulingTemplateDetail> srcList = siteTemplateDetailMapper.selectByExample(example);
		if (null == srcList || srcList.isEmpty()) {
			// 模板详情未找到
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("模板详情未找到");
			result.setSuccess(false);
			return result;
		}

		// 组装数据(按工位分组组合数据)
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		// 工位分组列表
		List<SiteTemplateDetailDO> dstList = new ArrayList<SiteTemplateDetailDO>();
		// 工位分组下的席位列表
		List<WorkSeatSchedulingDO> seatList = new ArrayList<WorkSeatSchedulingDO>();
		int groupIndex = srcList.get(0).getSeatGroupIndex();

		// 以分组序号为单位组织席位数据
		for (int i = 0; i < srcList.size(); i++) {
			SiteSchedulingTemplateDetail data = srcList.get(i);
			if (groupIndex != data.getSeatGroupIndex()) {
				SiteTemplateDetailDO detailDO = new SiteTemplateDetailDO();
				detailDO.setSeatGroupIndex(groupIndex);
				detailDO.setSeatList(seatList);
				dstList.add(detailDO);

				groupIndex = data.getSeatGroupIndex();
				seatList = new ArrayList<WorkSeatSchedulingDO>();
			}

			// 保存席位数据
			WorkSeatSchedulingDO seatSchedulingDO = new WorkSeatSchedulingDO();
			seatSchedulingDO.setId(data.getId());
			seatSchedulingDO.setPlanStartOn(data.getPlanStartOn());
			seatSchedulingDO.setPlanStartOnStr(sdf.format(data.getPlanStartOn()));
			seatSchedulingDO.setStatus(data.getStatus());

			seatList.add(seatSchedulingDO);
		}

		if (!seatList.isEmpty()) {
			SiteTemplateDetailDO detailDO = new SiteTemplateDetailDO();
			detailDO.setSeatGroupIndex(groupIndex);
			detailDO.setSeatList(seatList);
			dstList.add(detailDO);
		}

		// 分页处理
		if (query.isPage()) {
			List<SiteTemplateDetailDO> dstPageList = new ArrayList<SiteTemplateDetailDO>();
			for (int i = query.getStart(); i < (query.getStart() + query.getPageRows()); i++) {
				if (i < dstList.size()) {
					dstPageList.add(dstList.get(i));
				} else {
					break;
				}
			}
			result.setModel(ResultDO.FIRST_MODEL_KEY, dstPageList);
		} else {
			result.setModel(ResultDO.FIRST_MODEL_KEY, dstList);
		}
		result.setModel(ResultSupport.SECOND_MODEL_KEY, dstList.size());

		return result;
	}

	/**
	 * 根据工位分组序号删除工位分组 <b>Description:</b><br>
	 * 
	 * @param domain
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午3:59:36 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO delete(SiteTemplateDetailDO domain) {
		// 删除组
		ResultDO result = new ResultSupport();
		if (isNumberInValid(domain.getTemplateID()) || null == domain.getSeatGroupIndexs()
				|| domain.getSeatGroupIndexs().length < 1) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			return result;
		}

		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andTemplateIDEqualTo(domain.getTemplateID());
		criteria.andSeatGroupIndexIn(Arrays.asList(domain.getSeatGroupIndexs()));
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		SiteSchedulingTemplateDetail detail = new SiteSchedulingTemplateDetail();
		detail.setIsDelete(BonConstant.DB_DELETE);
		detail.setModifitime(Calendar.getInstance().getTime());
		detail.setModifiID(domain.getModifiID());
		detail.setModifi(domain.getModifi());

		int ret = siteTemplateDetailMapper.updateByExampleSelective(detail, example);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("工位分组删除失败");
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 工位分组增加席位 <b>Description:</b><br>
	 * 
	 * @param detailDO
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午4:01:07 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO addSeat(SiteTemplateDetailDO detailDO) {

		// 添加席位
		ResultDO result = new ResultSupport();
		// 参数判断
		if (isNumberInValid(detailDO.getTemplateID())) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("模板ID为空");
			result.setSuccess(false);
			return result;
		}
		// 判断该时段是否已存在
		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andTemplateIDEqualTo(detailDO.getTemplateID());
		Date planStartOn = null;
		try {
			planStartOn = new SimpleDateFormat("HH:mm").parse(detailDO.getPlanStartOnStr());
		} catch (ParseException e1) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("拍摄时段格式错误");
			result.setSuccess(false);
			return result;
		}
		criteria.andPlanStartOnEqualTo(planStartOn);
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);

		int count = siteTemplateDetailMapper.countByExample(example);
		if (count > 0) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("拍摄时段重复");
			result.setSuccess(false);
			return result;
		}
		// 添加席位
		SiteSchedulingTemplateDetail detail = new SiteSchedulingTemplateDetail();
		if (!BeanUtilsExtends.copyProperties(detail, detailDO)) {
			// 拷贝错误
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("数据格式拷贝错误");
			result.setSuccess(false);
			return result;
		}
		detail.setPlanStartOn(planStartOn);
		detail.setStatus(BonConstant.SEAT_STATUS_ENABLE);
		detail.setIsDelete(BonConstant.DB_NORMAL);
		detail.setCreatetime(Calendar.getInstance().getTime());
		detail.setAuthorID(detailDO.getAuthorID());
		detail.setAuthor(detailDO.getAuthor());

		int ret = siteTemplateDetailMapper.insert(detail);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("席位添加失败");
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 编辑席位（拍摄时段） <b>Description:</b><br>
	 * 
	 * @param detailDO
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午4:01:26 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO editSeat(SiteTemplateDetailDO detailDO) {
		// 编辑席位
		ResultDO result = new ResultSupport();
		// 参数判断
		if (isNumberInValid(detailDO.getId())) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("ID为空");
			result.setSuccess(false);
			return result;
		}

		// 判断席位是否已存在
		SiteSchedulingTemplateDetail data = siteTemplateDetailMapper.selectByPrimaryKey(detailDO.getId());
		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andTemplateIDEqualTo(data.getTemplateID());
		criteria.andSeatGroupIndexEqualTo(data.getSeatGroupIndex());
		Date planStartOn = null;
		try {
			planStartOn = new SimpleDateFormat("HH:mm").parse(detailDO.getPlanStartOnStr());
		} catch (ParseException e1) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("拍摄时段格式错误");
			result.setSuccess(false);
			return result;
		}
		criteria.andPlanStartOnEqualTo(planStartOn);
		criteria.andIsDeleteEqualTo(BonConstant.DB_NORMAL);
		criteria.andIdNotEqualTo(detailDO.getId());

		int count = siteTemplateDetailMapper.countByExample(example);
		if (count > 0) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("拍摄时段重复");
			result.setSuccess(false);
			return result;
		}

		SiteSchedulingTemplateDetail detail = new SiteSchedulingTemplateDetail();
		detail.setId(detailDO.getId());
		detail.setPlanStartOn(planStartOn);
		detail.setModifitime(Calendar.getInstance().getTime());
		detail.setModifiID(detailDO.getModifiID());
		detail.setModifi(detailDO.getModifi());

		int ret = siteTemplateDetailMapper.updateByPrimaryKeySelective(detail);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("席位编辑失败");
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 设置席位状态（0启用，-1禁用） <b>Description:</b><br>
	 * 
	 * @param detailDO
	 * @return ResultDO
	 * @Note <b>Author:</b> Reading.Reagan <br>
	 *       <b>Date:</b> 2018年9月18日 下午4:01:42 <br>
	 *       <b>Version:</b> 1.0
	 */
	public ResultDO seatStatus(SiteTemplateDetailDO detailDO) {
		// 编辑席位
		ResultDO result = new ResultSupport();
		// 参数判断
		if (isNumberInValid(detailDO.getId())) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("ID为空");
			result.setSuccess(false);
			return result;
		}

		SiteSchedulingTemplateDetail detail = new SiteSchedulingTemplateDetail();
		detail.setId(detailDO.getId());
		detail.setStatus(detailDO.getStatus());
		detail.setModifitime(Calendar.getInstance().getTime());
		detail.setModifiID(detailDO.getModifiID());
		detail.setModifi(detailDO.getModifi());

		int ret = siteTemplateDetailMapper.updateByPrimaryKeySelective(detail);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("席位编辑失败");
			result.setSuccess(false);
		}
		return result;
	}

	@Override
	public ResultDO deleteSeat(SiteTemplateDetailDO detailDO) {

		ResultDO result = new ResultSupport();
		// 参数判断
		if (null == detailDO.getIds() || detailDO.getIds().length < 1) {
			// 参数错误
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("ID为空");
			result.setSuccess(false);
			return result;
		}

		SiteSchedulingTemplateDetailExample example = new SiteSchedulingTemplateDetailExample();
		SiteSchedulingTemplateDetailExample.Criteria criteria = example.createCriteria();
		criteria.andIdIn(Arrays.asList(detailDO.getIds()));

		int ret = siteTemplateDetailMapper.deleteByExample(example);
		if (ret < 1) {
			result.setErrorCode(ResultDO.SYSTEM_EXCEPTION_ERROR);
			result.setErrorMsg("席位删除失败");
			result.setSuccess(false);
		}
		return result;
	}

}
